package server.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import server.business.pojo.PatientTransfusionRecord;
import server.business.service.RecordService;
import server.business.vo.Result;
import server.business.vo.ResultExpand;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/blood_record")
public class RecordController {

    @Autowired
    private RecordService recordService;

    @RequestMapping("/blood_record")
    public String toSample(){
        return "pages/TransfusionalRecording";
    }

    //查询数据
    @RequestMapping("/normal/query")
    @ResponseBody
    public List<PatientTransfusionRecord> queryData(){
        List<PatientTransfusionRecord> list = recordService.queryData();
        return list;
    }

    /**
     * 获取页面
     * 不良反应分页查询
     */
    @RequestMapping("/normal/listByPage")
    @ResponseBody
    public ResultExpand getPage(HttpServletRequest request, HttpServletResponse response){
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        IPage<PatientTransfusionRecord> samplePage = recordService.selectByPage(currentPage, pageSize);
        ResultExpand resultExpand = new ResultExpand("200", "成功", samplePage.getRecords(), currentPage, pageSize, samplePage.getTotal(), samplePage.getPages());
        response.setStatus(200);
        return resultExpand;
    }

    /**
     * 搜索不良反应记录
     *
     * @param request  请求
     * @param response 响应
     * @return {@link ResultExpand}
     */
    @RequestMapping("/normal/searchSample")
    @ResponseBody
    public ResultExpand searchSample(HttpServletRequest request, HttpServletResponse response){
        //前端获取的不良反应编号，患者姓名
        String transfusionNumber = request.getParameter("transfusionNumber");
        System.out.println(transfusionNumber);
        String name = request.getParameter("name");
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        //创建分页对象
        IPage<PatientTransfusionRecord> page = new Page<>(currentPage, pageSize);
        //创建查询条件
        QueryWrapper<PatientTransfusionRecord> queryWrapper = new QueryWrapper<>();
        if (transfusionNumber != "")
            queryWrapper.eq("transfusion_number", transfusionNumber);
        if (name != "")
            queryWrapper.like("`name`", name);
        //查询数据库
        recordService.page(page, queryWrapper);
        //返回的数据
        ResultExpand resultExpand = new ResultExpand();
        resultExpand.setCurrent(currentPage).setPageSize(pageSize).setTotal(page.getTotal()).setPages(page.getPages());
        resultExpand.setCode("200");
        resultExpand.setMsg("搜索成功");
        resultExpand.setData(page.getRecords());
        return resultExpand;
    }

    //删除数据
    @DeleteMapping("/normal/deleteById")
    @ResponseBody
    public Result deleteById(@RequestBody JSONObject jsonPram){
        JSONObject jsonObject = new JSONObject(jsonPram);
        PatientTransfusionRecord patientTransfusionRecord = jsonObject.getObject("PatientTransfusionRecord", PatientTransfusionRecord.class);
        System.out.println(jsonPram);
        boolean success = recordService.removeById(jsonPram);
        Result result = new Result();
        if(success) {
            result.setCode("200");
            result.setMsg("删除成功");
        }else{
            result.setCode("500");
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 批量删除
     */
    @RequestMapping("/normal/batchDelete")
    @ResponseBody
    public Result batchDelete(@RequestBody ArrayList<Integer> ids) {
        System.out.println(ids);
        boolean success = recordService.removeByIds(ids);
        Result result = new Result();
        if (success) {
            result.setCode("200");
            result.setMsg("删除成功");
        } else {
            result.setCode("500");
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 增加输血记录
     *
     * @param
     * @return {@link Result}
     */
    @RequestMapping(value = "/normal/addRecord")
    @ResponseBody
    public Result addAdverseReaction(@RequestBody JSONObject jsonPram) {
        JSONObject jsonObject = new JSONObject(jsonPram);
        PatientTransfusionRecord patientTransfusionRecord = jsonObject.getObject("patientTransfusionRecord", PatientTransfusionRecord.class);
        System.out.println(patientTransfusionRecord);
        patientTransfusionRecord.setGmtCreate(new Date());
        patientTransfusionRecord.setGmtModified(new Date());
        recordService.save(patientTransfusionRecord);
        Result result = new Result();
        result.setCode("200");
        result.setMsg("录入输血信息成功");
        return result;
    }

    /**
     * 修改记录
     *
     * @param
     * @return {@link Result}
     */
    @PutMapping(value = "/normal/reviseRecord")
    @ResponseBody
    public Result reviseAdverseReaction(@RequestBody JSONObject jsonPram) {
        JSONObject jsonObject = new JSONObject(jsonPram);
        PatientTransfusionRecord patientTransfusionRecord = jsonObject.getObject("patientTransfusionRecord", PatientTransfusionRecord.class);
        System.out.println(patientTransfusionRecord);
        patientTransfusionRecord.setGmtCreate(new Date());
        patientTransfusionRecord.setGmtModified(new Date());
        recordService.updateById(patientTransfusionRecord);
        Result result = new Result();
        result.setCode("200");
        result.setMsg("录入输血信息成功");
        return result;
    }

//    /**
//     * 下载excel
//     *
//     * @param request  请求
//     * @param response 响应
//     */
//    @RequestMapping("/blood_sample/downloadExcel")
////    @ResponseBody
//    public void downloadExcel(HttpServletRequest request, HttpServletResponse response){
//
//        //前端获取的样本ID、状态、操作员、时间范围
//        String sampleId = request.getParameter("sampleId");
//        String condition = request.getParameter("condition");
//        String operator = request.getParameter("operator");
//        String startTime = request.getParameter("startTime");
//        String endTime = request.getParameter("endTime");
//        try {
//            String filename = "血液样本";
//            String userAgent = request.getHeader("User-Agent");
//            if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
//                filename = URLEncoder.encode(filename,"UTF-8");            }else {
//                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
//            }
//            response.setContentType("application/json.ms-exce");
//            response.setCharacterEncoding("utf-8");
//            response.addHeader("Content-Disposition","filename = " + filename + ".xlsx");
//            QueryWrapper<AdverseReaction> queryWrapper = new QueryWrapper<>();
//            if (sampleId != "" && sampleId != null)
//                queryWrapper.like("id", sampleId);
//            if (condition != "" && condition != null)
//                queryWrapper.eq("`condition`", condition);
//            if(operator != "" && operator != null)
//                queryWrapper.eq("operator", operator);
//            if(startTime != "" && startTime != null)
//                queryWrapper.ge("collect_time", startTime);
//            if(endTime != "" && endTime != null)
//                queryWrapper.le("collect_time", endTime + " 23:59:59");
//            List<AdverseReaction> SampleDataList = indexService.list(queryWrapper);
//            EasyExcel.write(response.getOutputStream(),AdverseReaction.class).sheet("sheet").doWrite(SampleDataList);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
